package griffin.website;


import griffin.logic.userLogic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.content.pm.ActivityInfo;

public class bookmark extends Activity {
	private static final String TAG = "[bookmark]";
    private static final String SOAP_ACTION = "http://tempuri.org/getBookmarks";
    private static final String SOAP_ACTION2 = "http://tempuri.org/deleteBookmarks";
    private static final String METHOD_NAME = "getBookmarks";
    private static final String METHOD_NAME2 = "deleteBookmarks";
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://griffin.ciandt.cn/Sservice1.asmx";
    private List<Map<String, Object>> bookmarkList = new ArrayList<Map<String, Object>>();
    private ListView listView = null;
	private int loginuserid = 0;
	userLogic userlogic = new userLogic(this);

    @Override
    protected void onCreate(Bundle savedInstanceState){
    	Log.d(TAG, "[onCreate...1] ");	
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.bookmark);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		Init();
	}
	@Override
	public void onResume() {
		super.onResume();	
		Log.d(TAG, "[onResume...] ");	
		
		Init();
	}
	
	private void Init(){
		getLoginInfo();
		if (isLogin())
		{
			getBookmarkList();
		}
		else
		{
			askloginTip();
		}
	}

    
	private void getLoginInfo() {
		AtomicReference<String> strUsername = new AtomicReference<String>("");
    	AtomicReference<String> strPassword = new AtomicReference<String>("");
    	AtomicInteger userid = new AtomicInteger(0);
		if(userlogic.getLoginUser(strUsername, strPassword, userid)){
			loginuserid = userid.get();
		}
	}

	private Boolean isLogin()
	{
		if (loginuserid == 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	private void getBookmarkList() {
		bookmarkList.clear();
		listView = (ListView)this.findViewById(R.id.bookmarklist);
		listView.setAdapter(new BookMarkListAdapter());
		
		Log.d(TAG, "setAdapter");
	}
	
	private void askloginTip() {
		AlertDialog.Builder builder= new AlertDialog.Builder(bookmark.this);
		builder.setTitle("You are not sign in.Login now?").setPositiveButton("Yes!",new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface arg0, int arg1) {
				Intent intent = new Intent(bookmark.this,Login.class);  
				startActivity(intent);  
			}
		});
		builder.setCancelable(false).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
			public void onClick(DialogInterface dialog, int id) { 
				dialog.cancel(); 									
			} 
		});
		builder.create();
		builder.show();
	}
	
    class BookMarkListAdapter extends SimpleAdapter
    {
		public BookMarkListAdapter() {
			super(bookmark.this,getBookmarkData(loginuserid),R.layout.bookmarklistview,
					new String[]{"Bookmarkname"},
					new int[]{R.id.bookmarkname});
		}
    	
    	public View getView(int position,View convertView,ViewGroup parent)
    	{
    		HashMap<String, Object> item = (HashMap<String, Object>) bookmarkList.get(position);    
    		
    		LayoutInflater inflater = getLayoutInflater();
    		View row=inflater.inflate(R.layout.bookmarklistview, parent, false);
    		TextView label = (TextView)row.findViewById(R.id.bookmarkname);
    		
    		label.setText((String)item.get("Bookmarkname"));
    		label.setTag((String)item.get("Bookmarkurl"));
    		label.setOnClickListener(new BookmarkClickListener());
    		
    		ImageButton reducebookmark = (ImageButton)row.findViewById(R.id.minusbookmark);
    		reducebookmark.setTag((String)item.get("Bookmarkname"));
    		reducebookmark.setOnClickListener(new reduceButtonListener());
    		
    		Log.d(TAG, "[getView ].position("+position+")");
    		
    		return row;
    		
    	}
    	
    }
    
    private List<Map<String, Object>> getBookmarkData(int userid){
		if (userid != 0)
		{
			try{
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		        request.addProperty("userid", userid);
	
		        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		        envelope.dotNet=true;
		        envelope.setOutputSoapObject(request);
	
		        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		        androidHttpTransport.call(SOAP_ACTION, envelope);
	
		        Object result = (Object)envelope.getResponse();  
		        try 
		        {   
		        	JSONObject jsonObj = new JSONObject(result.toString());
		            JSONArray bookmarkArr = jsonObj.getJSONArray("bookmarks");
		            
		            for(int i = 0; i < bookmarkArr.length(); i++)
		            {
		            	Map<String, Object> map = new HashMap<String, Object>();
		            	map.put("Bookmarkurl", bookmarkArr.getJSONObject(i).getString("Bookmarkurl"));
		            	map.put("Bookmarkname", bookmarkArr.getJSONObject(i).getString("Bookmarkname"));
		            	bookmarkList.add(map);
		            }
		        } 
		        catch (JSONException e) 
		        {   
		        	e.printStackTrace();   
		        }    
			}catch(Exception ex){
				ex.printStackTrace(); 
			}
		}
		
		return bookmarkList;
	}
    
    class reduceButtonListener implements View.OnClickListener
    {
    	public void onClick(View v)
    	{
    		ImageButton reducebookmark=(ImageButton)v;
    		String bookmarkname = reducebookmark.getTag().toString().trim();
    		
	    	deleteBookmark(loginuserid, bookmarkname);
	    	refreshBookmarkList();
    	}
    }
    
    class BookmarkClickListener implements View.OnClickListener
    {
    	public void onClick(View v)
    	{
    		TextView clickbookmark = (TextView)v;
    		String bookmarkurl = clickbookmark.getTag().toString().trim();
    		openUrl(bookmarkurl);
    	}
    }
    
	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent); 
	}
    
    private void deleteBookmark(int userid, String bookmarkname)
    {  	
		if (userid != 0)
		{
			try{
				SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
		        request.addProperty("userid", userid);
		        request.addProperty("bookmarkName", bookmarkname);
	
		        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		        envelope.dotNet=true;
		        envelope.setOutputSoapObject(request);
	
		        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		        androidHttpTransport.call(SOAP_ACTION2, envelope);
	
//		        Object result = (Object)envelope.getResponse();    
			}catch(Exception ex){
				ex.printStackTrace(); 
			}
		}
    }
    
    private void refreshBookmarkList()
    {
    	getBookmarkList();
    }
    
 	public void DisplayToast(String str)
 	{
 		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 	}

}